/**
 * 缺勤记录
 */
import React, { Fragment } from 'react';
import { Card, Form, Table, Row, Col, Button } from 'antd';
import { get as getPath } from 'object-path';
import { QuickForm, utils } from 'vv-frontend-components';
import { connect } from 'umi';
import { history } from 'umi';
import { formatMessage } from 'umi';
import LinkTo from '@/components/LinkTo';
import Locale from '@/utils/locale';
import { download } from '@/utils/utils';

import AuthComponent from '@/utils/auth/AuthComponent';
import { Pagination } from '@/components';
import styles from './index.less';

const { deepTrim } = utils;

class AbsenceList extends React.Component {
    columnsAbsence = [
        {
            title: `${formatMessage({
                id: 'stat.absenceList.userNo'
            })}`,
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: `${formatMessage({
                id: 'stat.absenceList.userName'
            })}`,
            dataIndex: 'userName',
            key: 'userName'
        },
        {
            title: `${formatMessage({
                id: 'stat.absenceList.departName'
            })}`,
            dataIndex: 'departName',
            key: 'departName'
        },
        {
            title: `${formatMessage({
                id: 'stat.absenceList.exceptionName'
            })}`,
            dataIndex: 'exceptionName',
            key: 'exceptionName'
        },
        {
            title: `${formatMessage({
                id: 'stat.absence.exceptionDate'
            })}`,
            dataIndex: 'exceptionDate',
            key: 'exceptionDate',
            render: (text, record) => <span>{record.exceptionDate}</span>,
            sorter: () => {}
        },
        {
            title: `${formatMessage({
                id: 'stat.absence.action'
            })}`,
            dataIndex: 'action',
            key: 'action',
            width: 120,
            render: (text, record) => (
                <span>
                    <LinkTo
                        to="/office/personnelManagement/attendance/timetag/attendRecord/clockRecord"
                        query={{
                            id: record.employeeCode,
                            name: record.userName,
                            signDate: record.exceptionDate
                        }}
                    >
                        {formatMessage({
                            id: 'stat.absence.seeDetail'
                        })}
                    </LinkTo>
                </span>
            )
        }
    ];

    ORDER_MAP = {
        'exception_date asc': 'ascend',
        'exception_date desc': 'descend'
    };

    constructor(props) {
        super(props);
        const {
            location: { query }
        } = this.props;
        this.state = {
            orderByField: query.orderByField,
            sorter: ''
        };
    }

    async componentDidMount() {
        const { location } = this.props;
        const {
            query: { orderByField }
        } = location;

        this.columnsAbsence[4].sortOrder = this.ORDER_MAP[orderByField];
        setTimeout(() => {
            // 为了确保form中的值已经更新
            this.fetchList();
        });
    }

    getParams = _query => {
        const {
            form: { getFieldsValue },
            location: { query }
        } = this.props;
        const { companyDepart = {}, date = { range: [] }, userName } = getFieldsValue();
        const parame = {
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            employeeName: userName || '',
            pageNo: query.pageNo,
            pageSize: query.pageSize,
            orderByField: getPath(this.state, 'orderByField', ''),
            ..._query
        };
        return parame;
    };

    // 获取列表
    fetchList = () => {
        const { dispatch } = this.props;
        dispatch(
            deepTrim({
                type: 'abnormalRank/fetchAbcense',
                payload: this.getParams()
            })
        );
    };

    handelReplaceRoute = _query => {
        const { location, form } = this.props;
        const { getFieldsValue } = form;
        const { query, pathname } = location;
        const { date = {} } = getFieldsValue();
        const { type, quarter } = date;
        history.push({
            pathname,
            query: {
                ...query,
                ...this.getParams(_query),
                dateType: type,
                quarter,
                key: 'absencelist'
            }
        });
    };

    handleSubmit = async e => {
        e.preventDefault();
        this.handelReplaceRoute({ pageNo: 1 });
        this.fetchList();
    };

    /** 导出 */
    handelExport = () => {
        const { pageNo, pageSize, ...other } = this.getParams();
        const { dispatch } = this.props;
        download({
            getData: () =>
                dispatch({
                    type: 'abnormalRank/fetchAbsenceExport',
                    payload: deepTrim(other)
                })
        });
    };

    // 表格表头点击切换排序
    changeTable = async (pagination, filters, sorters) => {
        const { sorter } = this.state;

        let orderBy;
        let sorterField;

        let finalQuery = {};
        if (sorters && sorters.field && sorters.order) {
            if (sorters.field === 'exceptionDate') {
                sorterField = 'exception_date';
            }
            const order = sorters.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
            this.setState({
                orderByField: orderBy
            });
        } else if (typeof sorters === 'string') {
            this.setState({
                orderByField: ''
            });
        }
        if (sorters && sorters !== sorter) {
            this.setState({
                sorter: sorters,
                orderByField: orderBy
            });
            finalQuery = { pageNo: 1 };
        }
        this.columnsAbsence[4].sortOrder = this.ORDER_MAP[orderBy];

        this.handelReplaceRoute(finalQuery);
        setTimeout(() => {
            this.fetchList();
        });
    };

    changePagination = _pagination => {
        this.handelReplaceRoute({ pageNo: _pagination.current, pageSize: _pagination.pageSize });
        setTimeout(() => {
            this.fetchList();
        });
    };

    render() {
        const { loading, abnormalRank, form, authCode, location } = this.props;
        const { query } = location;
        const { absenceData, paginationAbsence } = abnormalRank;
        const { locale } = new Locale('stat.overtime');

        return (
            <Fragment>
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <Card
                        className={styles.bordered}
                        bordered={false}
                        title={formatMessage({
                            id: 'stat.absence.cardtitle'
                        })}
                        headStyle={{ padding: '0' }}
                        bodyStyle={{ padding: '16px 0' }}
                        extra={
                            <Fragment>
                                <Button type="primary" htmlType="submit">
                                    {locale('form.search', false)}
                                </Button>
                                <AuthComponent code={authCode}>
                                    <Button
                                        onClick={this.handelExport}
                                        style={{ marginLeft: '10px' }}
                                        disabled={loading}
                                    >
                                        导出
                                    </Button>
                                </AuthComponent>
                            </Fragment>
                        }
                    >
                        <Row type="flex" className="searchTitle">
                            <Col>
                                <QuickForm form={form} config={getPath(this.props, 'config')} />
                            </Col>
                        </Row>
                    </Card>
                </Form>
                <Card bordered={false} className={styles.cardAbnorRank}>
                    <Table
                        dataSource={absenceData}
                        columns={this.columnsAbsence}
                        loading={loading}
                        rowKey="id"
                        onChange={this.changeTable}
                        pagination={false}
                    />
                    <Pagination
                        onChange={this.changePagination}
                        total={paginationAbsence.total}
                        current={query.pageNo}
                        pageSize={query.pageSize}
                        loading={loading}
                    />
                </Card>
            </Fragment>
        );
    }
}

export default connect(({ abnormalRank, loading }) => ({
    abnormalRank,
    loading: loading.models.abnormalRank
}))(Form.create()(AbsenceList));
